package com.bidevalution.business.impl;

import com.bidevalution.business.common.AnalysisZip4jUtil;
import com.bidevalution.business.common.UnicodeReader;
import com.bidevalution.business.handler.TbXfHandler;
import com.bidevalution.business.service.BidCaseStatService;
import com.bidevalution.dao.entity.BeBidFile;
import com.bidevalution.dao.entity.BeSectionEnterprise;
import com.bidevalution.dao.entity.BeSectionInfo;
import com.bidevalution.dao.entity.SectionInfoResult;
import com.bidevalution.dao.mapper.BeBidFileMapper;
import com.bidevalution.dao.mapper.BeSectionEnterpriseMapper;
import com.bidevalution.dao.mapper.BeSectionInfoMapper;
import com.bidevalution.dao.mapper.BidCaseStatMapper;
import com.bidevalution.support.util.FileUtil;
import com.qtp.core.config.PropertiesTookit;
import com.bidevalution.support.util.UrlUtil;
import com.qtp.core.model.Paging;
import com.qtp.core.util.FileUtils;
import com.qtp.core.util.GsonUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @Description 开评标情况统计接口实现类
 * @Date        2020-02-10 9:13
 * @Author      lhl
 */
@Log4j2
@Service
public class BidCaseStatServiceImpl implements BidCaseStatService {

    @Autowired(required = false)
    BidCaseStatMapper bidCaseStatMapper;
    @Autowired(required = false)
    private BeSectionEnterpriseMapper beSectionEnterpriseMapper;
    @Autowired(required = false)
    private BeBidFileMapper beBidFileMapper;
    @Autowired(required = false)
    private BeSectionInfoMapper beSectionInfoMapper;

    private static final String FILE_SERVER_URL = PropertiesTookit.getValue("FILE_SERVER_URL")+"UploadedFile/";

    @Value("${download.file.path}")
    private String downloadFilePath;


    @Override
    public Paging<SectionInfoResult> getSectionPaging(Map<String, Object> params) {
        long count = bidCaseStatMapper.getSectionCount(params);
        if (count == 0){
            return new Paging(0L,new ArrayList());
        }else {
            return new Paging(count,bidCaseStatMapper.getSectionList(params));
        }
    }

    @Override
    public Map<String, Object> getBidFileBrandStat(Map<String, Object> params) {
        log.info("LOG[]getBidDocSum[]{},params={}", "获取标书品牌汇总",GsonUtil.toJsonWithGson(params));
        try {
            return bidCaseStatMapper.getBidFileBrandStat(params);
        }catch (Exception e){
            log.error("LOG[]getBidDocSum[]{},error={},params={}","获取标书品牌汇总异常", GsonUtil.toJsonWithGson(e),GsonUtil.toJsonWithGson(params));
        }
        return null;
    }

    @Override
    public List<Map<String, Object>> getBidUnitList(Map<String, Object> params) {
        log.info("LOG[]getBidUnitList[]{},params={}", "获取投标明细",GsonUtil.toJsonWithGson(params));
        try {
            return bidCaseStatMapper.getBidUnitList(params);
        }catch (Exception e){
            log.error("LOG[]getBidUnitList[]{},error={},params={}","获取投标明细异常", GsonUtil.toJsonWithGson(e),GsonUtil.toJsonWithGson(params));
        }
        return null;
    }

    @Override
    public List<Map<String, Object>> getAreaProjectBidDetail(Map<String, Object> params) {
        log.info("LOG[]getAreaProjectBidDetail[]{},params={}", "获取某地区的项目投标明细",GsonUtil.toJsonWithGson(params));
        try {
            return bidCaseStatMapper.getAreaProjectBidDetail(params);
        }catch (Exception e){
            log.error("LOG[]getAreaProjectBidDetail[]{},error={},params={}","获取某地区的项目投标明细异常",GsonUtil.toJsonWithGson(e),GsonUtil.toJsonWithGson(params));
        }
        return null;
    }

    @Override
    public List<Map<String, Object>> getExportPingShenQuJianData(String sectionId, String sectionStepId) {
        return bidCaseStatMapper.getExportPingShenQuJianData(sectionId,sectionStepId);
    }

    @Override
    public void exportEntPdf(String entIds, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String sectionCode = null;
        if(StringUtils.isNotBlank(entIds)) {
            String[] ids = entIds.split(",");
            //获取标段编号
            BeSectionEnterprise enterprise = beSectionEnterpriseMapper.selectByPrimaryKey(ids[0]);
            if(enterprise!=null) {
                String sectionId = enterprise.getSectionId();
                BeSectionInfo sectionInfo = beSectionInfoMapper.selectByPrimaryKey(sectionId);
                sectionCode = sectionInfo.getSectionCode();
            } else {
                log.error("无法查询到企业信息，seq_id="+ids[0]);
                return;
            }
            //获取pt_enterprise_id
            List<String> ptEntIds = beSectionEnterpriseMapper.findPtEntIdsByIds(ids);
            if(ptEntIds!=null && !ptEntIds.isEmpty()) {
                //将投标文件下载到评标服务
                List<String> filePaths = downloadTbs(ptEntIds);
                if(filePaths!=null && !filePaths.isEmpty()) {
                    //每个批次生成一个目录
                    String batchDir = System.getProperty("user.dir") + File.separator +"exportPdfTemp"
                            + File.separator + sectionCode;
                    //解压投标文件，获取pdf
                    for(String filePath:filePaths) {
                        unZipTb(filePath, batchDir);
                    }
                    //将整个文件夹打包
                    AnalysisZip4jUtil.zip(batchDir, batchDir+".zip");
                    //前端下载压缩包
                    FileUtils.downloadFile(batchDir+".zip",sectionCode+".zip",request,response);
                    //删除临时文件
                    org.apache.commons.io.FileUtils.deleteDirectory(new File(batchDir));
                    org.apache.commons.io.FileUtils.deleteQuietly(new File(batchDir+".zip"));
                    for(String filePath:filePaths) {
                        org.apache.commons.io.FileUtils.deleteQuietly(new File(filePath));
                    }
                }
            }
        }
    }

    /**
     * 下载投标文件
     * @param ptEntIds
     * @return
     * @throws Exception
     */
    private List<String> downloadTbs(List<String> ptEntIds) throws Exception {
        List<String> filePaths = new ArrayList<>();
        //根据pt_enterprise_id获取任务表对象
        List<BeBidFile> bidFiles = beBidFileMapper.findFilePathByEntIds(ptEntIds);
        String fileDownloadUrl = UrlUtil.spliceUrl(downloadFilePath,"UploadedFile/");
        for(BeBidFile bidFile:bidFiles) {
            //将投标文件下载到指定目录下
            String path = bidFile.getFilePath();
            String fileId = bidFile.getFileId();
            String ext = path.split("\\.")[path.split("\\.").length-1];
            String filePath = System.getProperty("user.dir") + File.separator +"exportPdfTemp" + File.separator
                    + UUID.randomUUID().toString()+"."+ext;
            FileUtil.downloadFile(fileDownloadUrl,fileId,filePath);
            filePaths.add(filePath);
        }
        return filePaths;
    }

    /**
     * 解压并获取投标文件的pdf
     */
    private void unZipTb(String filePath, String batchDir) throws ParserConfigurationException, SAXException, IOException {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser();
        XMLReader reader = saxParser.getXMLReader();
        TbXfHandler tbXfHandler = new TbXfHandler(batchDir);
        reader.setContentHandler(tbXfHandler);
        File xfXml = new File(filePath);
        reader.parse(new InputSource(new UnicodeReader(new FileInputStream(xfXml), "UTF-8")));
    }
}
